import * as types from './mutation-types'
import * as constant from '../../common/constant'
import { transform, untransform } from '../../common/uri'
import * as utils from '../../common/utils'
import Vue from 'vue'
import axios from 'axios'
import route from '@/router/'
import { m, notify, closeAllNotifications} from "@/store/yg/common/local"

axios.defaults.withCredentials=true;
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';

function loadBadge(state) {
  var tablist = state.entry.tab;
  if (tablist) {
    for (var i = 0; i < tablist.length; ++i) {
      var tab = tablist[i];
      if (tab.badge) {
        var tabUri = tab.uri;
        var uri = '/api/consume/badge?uri=' + tabUri;

        if (tab.tabSettingId) {x
          uri += '&id=' + tab.tabSettingId;
        }
        axios.post(constant.API_SERVER + uri).then(response => {
            Vue.set(state.badges, response.data.uri, response.data.total);
          }, response => {
          }
        );
      }
    }
  }
}

function firstSeed(state, k) {
  if ( ! state.entry.table) {
    return k;
  }
  var field = k;
  var seeks = state.entry.table.thead.seed;

  for (var i = 0; i < seeks.length; ++i) {
    if ( ! seeks[i]) {
      continue;
    }
    var firstSeed = seeks[i];
    if (firstSeed.field == k) {
      Vue.set(state.seek.seekText, i, firstSeed.caption);
      return k;
    }
  }
  return k;
}


function defaultCondition(dc, user) {
  if ( ! dc) {
    return true;
  }
  for (let i = 0; i < dc.length; ++i) {
    let c = dc[i];
    let field = c.field.replace('user.', '');

    if ( ! user[field]) {
      return false;
    }
    let vs = [].concat(user[field]);
    if (utils.intersection(vs, c.values).length <= 0) {
      return false;
    }
  }

  return true;
}

function fillSeeds(state, datas, seeks, uriIndex) {
  var seeds = {};

  if (undefined == state.entry.table) {
    return;
  }
  if ( ! seeks) {
    seeks = state.entry.table.thead.seed;
  }
  if ( ! seeks) {
    return;
  }
  state.entry.table.thead.seed = seeks;

  for (var i = 0; i < seeks.length; ++i) {
    if ( ! seeks[i]) {
      continue;
    }
    var type = seeks[i].type;
    var field = seeks[i].field;
    var convert = seeks[i].convert;
    if (type == 'date') {
      seeds[field + '__start'] = '';
      seeds[field + '__end'] = '';
      seeds[field + '__end_date'] = true;
    }
    if (type == 'datetime' || type == 'range') {
      seeds[field + '__start'] = '';
      seeds[field + '__end'] = '';
    } else if (type == 'cascader') {
      seeds[field] = [];
    } else {
      seeds[field] = '';
    }
    if (convert) {
      Vue.set(state.seek.seekConvert, field, convert);
    }

    Vue.set(state.seek.autoUpper, field, true === seeks[i]['auto-upper']);
    Vue.set(state.seek.autoLower, field, true === seeks[i]['auto-lower']);
    Vue.set(state.seek.seekExact, field, false !== seeks[i].exact);
    Vue.set(state.seek.seekMultipleLine, field, seeks[i].type == 'textarea');

    let defualtValue = seeks[i].default;
    let dc = seeks[i]['default-condition'];
    let user = JSON.parse(localStorage.user);
    if ((undefined !== defualtValue && null !== defualtValue) && uriIndex && defaultCondition(dc, user)) {
      defualtValue += '';
      if (defualtValue.indexOf("user.") == 0) {
        defualtValue = user[defualtValue.replace('user.', '')];
      }
      seeds[field] = defualtValue;
      state.seedsDefaultValues[uriIndex] = {};
      state.seedsDefaultValues[uriIndex][field] = defualtValue;
    }
  }
  for (var i = 0; i < datas.length; ++i) {
    var d = datas[i];
    var field = firstSeed(state, d['field']);
    if (d['value']) {
      seeds[field] = d['value'];
    } else if (d['values']) {
      let vs = [];
      for (let v in d['values']) {
        vs.push(d['values'][v] + '');
      }
      d['values'] = vs;
      seeds[field] = d['values'];
    } else {
      if (d['start']) {
        seeds[field + '__start'] = d['start'];
      }
      if (d['end']) {
        seeds[field + '__end'] = d['end'];
      }
    }
  }

  Vue.set(state.seek, 'seeds', seeds);
}

function fillSorter(state, orders) {
  if (orders[0]) {
    state.seek.sorter = firstSeed(state, orders[0].field);
    state.seek.desc = orders[0].desc;
  }
  state.seek.defaultSort = {};
  Vue.set(state.seek.defaultSort, 'prop', state.seek.sorter);
  Vue.set(state.seek.defaultSort, 'order', (state.seek.desc ? 'descending' : 'ascending'));
}

function loadTransforms(state) {
  if ( ! state.entry.table) {
    return;
  }
  if ( ! state.entry.table.tbody) {
    return;
  }
  var tds = state.entry.table.tbody.td;
  var datas = state.pageData.data;
  for (var i in tds) {
    var rows = tds[i].row;
    for (var j in rows) {
      var row = rows[j];
      for (var k in datas) {
        var data = datas[k];
        if (row.transform && data[row.field]) {
          var req = {bean: row.transform, arg: data[row.field]};
          loadTransform(state, req);
        }
        if (row.transform2 && data[row.field]) {
          var req = {bean: row.transform2, arg1: row.field, arg2: data[row.field]};
          loadTransform(state, req);
        }
      }
    }
  }
}

function initSources(state) {
  if ( ! state.entry.sources) {
    state.entry.sources = {};
  }
  for (let i in state.entry.table.thead.seed) {
    let seed = state.entry.table.thead.seed[i];
    if (seed.source && ! state.entry.sources[seed.source]) {
      state.entry.sources[seed.source] = {};
    }
  }
  for (let i in state.entry.table.tbody.td) {
    let td = state.entry.table.tbody.td[i];
    for (let j in td.row) {
      let row = td.row[j];
      if (row.source && ! state.entry.sources[row.source]) {
        state.entry.sources[row.source] = {};
      }
    }
  }
}

function loadSource(state, option) {
  var arg = '';
  var bean = option;
  var cached = true;

  if ('object' == typeof option) {
    bean = option.bean;
    arg = option.arg;
    cached = undefined === option.cached ? true : option.cached;
  }
  if ( ! bean) {
    return;
  }
  var beanKey = cached && arg ? (bean + ' ' + arg) : bean;
  if (cached && 
    state.entry.sources && 
    state.entry.sources[beanKey] && 
    Object.keys(state.entry.sources[beanKey]).length > 0) {
    return ;
  }

  if (cached && localStorage['options_' + beanKey] && ! constant.DEV_MODE) {
    Vue.set(state.entry.sources, beanKey, JSON.parse(localStorage['options_' + beanKey]));
    return;
  }

  var uri = "/api/entry/source?bean=" + bean;
  if (arg) {
    uri += "&arg=" + arg;
  }
  if (option.withParams) {
    uri += "&withParams=" + true;
  }

  axios.post(constant.API_SERVER + uri).then(response => {
      Vue.set(state.entry.sources, beanKey, response.data);
      if (cached) {
        localStorage['options_' + beanKey] = JSON.stringify(response.data);
      }
      utils.storeSource(state.entry.sources, 'options_' + beanKey);
    }, error => {
      console.log(error);
    }
  );
}

function loadTransform(state, req) {
  var arg = req.arg;
  var arg1 = req.arg1;
  var arg2 = req.arg2;
  var bean = req.bean;
  if ( ! bean) {
    return;
  }
  if ( (! arg) && (! arg1 || ! arg2)) {
    return;
  }

  var beanKey =  bean + "|" + (arg ? arg  : arg1 + "|" + arg2);
  if (state.transforms[beanKey]) {
    if ( ! state.entry.sources[bean]) {
      Vue.set(state.entry.sources, bean, {});
    }
    Vue.set(state.entry.sources[bean], arg, state.transforms[beanKey]);

    return ;
  }

  if (localStorage['transforms_' + beanKey] && ! constant.DEV_MODE) {
    Vue.set(state.transforms, beanKey, JSON.parse(localStorage['transforms_' + beanKey]));
    if ( ! state.entry.sources[bean]) {
      Vue.set(state.entry.sources, bean, {});
    }
    Vue.set(state.entry.sources[bean], arg, state.transforms[beanKey]);

    return;
  }

  var uri = arg ?
    "/api/entry/transform?bean=" + bean + "&arg=" + arg
    :
    "/api/entry/transform2?bean=" + bean + "&arg1=" + arg1 + "&arg2=" + arg2;

  axios.post(constant.API_SERVER + uri).then(response => {
      Vue.set(state.transforms, beanKey, response.data);
      localStorage['transforms_' + beanKey] = JSON.stringify(response.data);

      if ( ! state.entry.sources[bean]) {
        Vue.set(state.entry.sources, bean, {});
      }
      Vue.set(state.entry.sources[bean], arg, response.data);
    }, error => {
      console.log(error);
    }
  );
}

function loadPageData(state, uri, id) {
  state.pageData = {};
  let uriIndex = uri;
  let seeds = {};
  if (state.seedsDefaultValues[uriIndex]) {
    seeds = state.seedsDefaultValues[uriIndex];
  }
  state.seek = {
    seeds: seeds,
    index: 1,
    sorter: '',
    desc: true,
    indexGo: '',
    seedSwitch: {},
    seekText: {},
    seekExact: state.seek.seekExact,
    seekConvert: state.seek.seekConvert,
    autoUpper: state.seek.autoUpper,
    autoLower: state.seek.autoLower,
    seekMultipleLine: state.seek.seekMultipleLine
  };
  state.selectedCount = 0;
  state.selectAll = 0;
  state.selectedRows = {};
  state.allSelected = false;

  var mainUri = '/api/consume/fetch?uri=' + uri;

  if (id) {
    mainUri += '&id=' + id;
  }
  if (route.currentRoute.query.pid) {
    mainUri += '&pid=' + route.currentRoute.query.pid;
  }
  if (Object.keys(route.currentRoute.query).length > 0) {
    mainUri += '&q=' + encodeURI(JSON.stringify(route.currentRoute.query));
  }

  // JS Layout配置
  if (state.entry.client && state.entry.client.class) {
    mainUri += '&className=' + state.entry.client.class;
    mainUri += '&listName=' + state.entry.client.list;
    mainUri += '&countName=' + state.entry.client.count;
  }

  axios.post(constant.API_SERVER + mainUri).then(response => {
      if ( ! currentReqeust(uri, id)) {
        return;
      }

      Vue.set(state, 'pageData', response.data);

      if (state.pageData.queryPage) {
        state.seek.size = state.pageData.queryPage.size;
        state.seek.index = state.pageData.queryPage.index;
        state.seek.selectedField = state.pageData.queryPage.selectedField;
        fillSeeds(state, state.pageData.queryPage.datas);
        fillSorter(state, state.pageData.queryPage.orders);
      }
      loadTransforms(state);
    }, error => {
      // error callback
        utils.auth(error);
    }
  );
}

function seedSwitch(state, k) {
  var field = k;
  if (state.seek.seedSwitch[k]) {
    field = state.seek.seedSwitch[k];
  }
  return field;
}

function commitAction(state, uri, params, ids, callafter) {
  if ( ! ids) {
    ids = {};
  }
  let headers = {};
  headers["YG-UNIQUE-KEY"] = uri + new Date().getTime();

  axios({
    method: 'post',
    url: constant.API_SERVER + uri,
    data: ids,
    headers: headers,
  }).then(response => {
      state.response = response.data;
      loadPageData(state, untransform(params.uri), params.id);
      if (callafter) {
        (callafter)(state.response);
      }
      if (ids.length) {
        loadBadge(state);
      }
      notice(state.response);
    }, response => {
      if (callafter) {
        (callafter)(state.response);
      }
      notice({});
    }
  );
}

function notice(res) {
  var msg = res.message && true !== res.message  ? m(res.message) : (res.code == 200 ? '操作成功' :  '操作失败');
  var type = res.type ? res.type : (res.code == 200 ? 'success' : (res.code == 300 ? 'warning' : 'error'));
  notify({
    message: msg,
    type: type,
    position: 'bottom-right',
    dangerouslyUseHTMLString: true
  });
}

function currentReqeust(uri, id) {
    var routePath = untransform('#' + route.history.current.path);
    var currentPath = id ? uri + '/' + id : uri;
    currentPath = currentPath.replace('&id=', '/');

    return routePath == currentPath || routePath.indexOf(currentPath + '/') === 0;
}

function loadSearchTemplate(state, uri) {
  state.searchTemplateTags = [];
  uri = untransform(uri);
  axios.post(
    constant.API_SERVER + "/api/consume/loadSearchTemplate?uri=" + uri
  ).then(response => {
    state.searchTemplateTags = response.data;
  }, response => {
  }
  );
}

function querySessionNode(state) {
  var node = {};
  var datas = [];
  var seeds = state.seek.seeds;

  state.seek['selectedField'] = '';

  for (var k in seeds) {
    var data = {};
    if (k.endsWith('__end')) {
      continue;
    }
    data['field'] = seedSwitch(state, k);
    var value = seeds[k];

    value = utils.trim(value);
    if (!value) {
      continue;
    }
    if (typeof value == 'object' && !value.length) {
      continue;
    }
    if (k.endsWith('__end_date')) {
      continue;
    }
    if (k.endsWith('__date')) {
      data['start'] = value[0];
      data['end'] = value[1];
    }
    if (k.endsWith('__start') || k.endsWith('__end')) {
      data['field'] = seedSwitch(state, k.replace('__start', ''));
      data['start'] = value;
      if (seeds[data['field'] + "__end"]) {
        data['end'] = seeds[data['field'] + "__end"];
        if (seeds[data['field'] + "__end_date"] && data['end'].indexOf(' ') < 0) {
          data['end'] += ' 23:59:59';
        }
      }
    } else if (k.endsWith('__end')) {
       
    } else if (typeof value == 'object') {
      data['values'] = value;
    } else {

      if (state.seek.autoUpper[k]) {
        value = value.toUpperCase();
      } else if (state.seek.autoLower[k]) {
        value = value.toLowerCase();
      }

      data['like'] = false === state.seek.seekExact[k];
      data['value'] = value;
    }
    if (state.seek.seekMultipleLine[k]) {
      data['multipleLine'] = true;
    }
    var nk = k.replace('__start', '').replace('__end', '');
    if (state.seek.seekConvert[nk]) {
      data['convert'] = state.seek.seekConvert[nk];
    }
    datas.push(data);
    if (value && ! state.seek['selectedField']) {
      state.seek['selectedField'] = data['field'];
    }
  }
  node['datas'] = datas;

  if (state.seek.sorter) {
    var orders = [];
    var order = {};
    order['field'] = seedSwitch(state, state.seek.sorter);
    if (state.seek.desc) {
      order["desc"] = true;
    } else {
      order["asc"] = true;
    }

    if (state.entry.table) {
      var heads = state.entry.table.thead.head;
      for (var i = 0; i < heads.length; ++i) {
        var head = heads[i];
        if (!head) {
          continue;
        }

        if (head.field == order['field']) {
          order['convert'] = head['convert'];
          break;
        }
      }
    }

    orders.push(order);
    node['orders'] = orders;
  }
  node['size'] = state.seek['size'];
  node['index'] = state.seek['index'];
  node['selectedField'] = state.seek['selectedField'];

  return node;
}

function loadMainEntry(state, req) {
  var uri = req;
  state.uri = transform(uri);

  var id = '';
  if (req && req.uri) {
    uri = req.uri;
    id = req.id;
  }
  var ouri = uri;
  if (id && id.length < 3) {
    ouri += id;
  }
  uri = untransform(uri);
  state.entry = {};
  var mainUri = '/api/entry/main?uri=' + uri;
  if (id) {
    mainUri += '&id=' + id;
  }

  if (localStorage['main_' + ouri] && !constant.DEV_MODE) {
    return new Promise((resolve, reject) => {
      state.entry = JSON.parse(localStorage['main_' + ouri]);
      loadBadge(state);
      resolve(state);
    });
  }
  return new Promise((resolve, reject) => {
    axios.post(constant.API_SERVER + mainUri).then(response => {
      if (!currentReqeust(uri, id)) {
        return;
      }
      state.entry = response.data;

      localStorage['main_' + ouri] = JSON.stringify(state.entry);
      utils.storeSource(state.entry.sources, 'main_' + ouri);
      loadBadge(state);
      resolve(state);
      fillSeeds(state, [], null, uri);
    }, error => {
      utils.auth(error);
    });
  });
}


function saveQuerySession(state, req, node) {
  if ( ! node) {
    node = req.node ? req.node : querySessionNode(state);
  }

  if (req.by == 'search') {
    node['index'] = 1;
  }
  
  state.seekExpandFieldCount = 0;
  if (req.node) {
    fillSeeds(state, req.node.datas, req.node.datas);
  }

  var uri = untransform(req.uri);

  if (req.id) {
    uri += "&id=" + req.id;
  }

  for (var field in state.seek['seeds']) {
    if (state.seek['seeds'][field]) {
      if (state.seek['seeds'][field].length !== undefined) {
        if (state.seek['seeds'][field].length > 0) {
          state.seekExpandFieldCount++;
        }
      } else {
        state.seekExpandFieldCount++;
      }
    }
  }

  if ( ! node.size) {
    if ( ! state.node.size) {
      let user = JSON.parse(localStorage.user);
      if (user.pageSize) {
        state.node.size = user.pageSize;
      } else {
        state.node.size = 10;
      }
    }
    node.size = state.node.size;
  }

  axios.post(
    constant.API_SERVER + "/api/session/save?uri=" + uri,
    node,
  ).then(response => {
      loadPageData(state, uri);
    }, response => {
      // error callback
    }
  );
}

export default {
  [types.LOAD_BADGE](state) {
    loadBadge(state);
  },
  [types.LOAD_MAIN_ENTRY](state, req) {
    closeAllNotifications();
    Vue.set(state, 'switched', false);
    Vue.nextTick(() => {
      Vue.set(state, 'switched', true);
    })
  },
  [types.SAVE_MAIN_RESPONSE] (state, res) {
    state.response = res;
  },
  [types.LOAD_PAGE_DATA](state, req) {
    var uri = req;
    var id = '';
    if (req.uri) {
      uri = req.uri;
      id = req.id;
    }
    uri = untransform(uri);

    /*
      优先加载JS配置，如果无法加载则获取YAML配置
    */
    var e = null;
    try {
      e = require('@/layout/main' + uri + '/Entry.js');
    } catch(ex) {
    };

    if (e) {
      state.entry = e;
      initSources(state);
      for (let source in state.entry.sources) {
        if (0 == Object.keys(state.entry.sources[source]).length) {
          loadSource(state, source);
        }
      }
      loadPageData(state, uri, id);
    } else {
      loadMainEntry(state, req).then(res => {
        let uriIndex = uri;
        if (route.currentRoute.query['node']) {
          let node = querySessionNode(state);
          node.datas = JSON.parse(route.currentRoute.query['node']);
          delete route.currentRoute.query['node'];
          saveQuerySession(
            state, 
            {
              uri: uri,
              id: id,
              by: "search"
            },
            node
          );
        } else if (state.seedsDefaultValues[uriIndex] && Object.keys(state.seedsDefaultValues[uriIndex]).length > 0 && ! localStorage["seek_inited_" + uriIndex]) {
          saveQuerySession(state, {
            uri: uri,
            id: id,
            by: "search"
          });
        } else {
          loadPageData(state, uri, id);
        }
      }, error => {
        console.log(error);
      });
    }

    state.shouldReload = false;
  },
  [types.COMMIT_ACTION](state, data) {
    var commit = data.commit;
    var id = data.id;
    var mainUri = untransform(data.params.uri);
    var uri = '/api/consume/commit?uri=' + mainUri + '&f=' + commit.commit + "&id=" + id;
    if (data.type) {
      uri += '&type=' + data.type;
    }
    if (commit.class) {
      uri += '&class=' + commit.class;
    }
    commitAction(state, uri, data.params, data.ids, data.callafter);
  },
  [types.MARK_SHOULD_RELOAD] (state, should) {
    state.shouldReload = should;
  },
  [types.SAVE_SEEK_DATA] (state, seek) {
    seek.seekExact = state.seek.seekExact;
    seek.seekMultipleLine = state.seek.seekMultipleLine;
    seek.seekConvert = state.seek.seekConvert;
    seek.autoLower = state.seek.autoLower;
    seek.autoUpper = state.seek.autoUpper;
    state.seek = seek;
  },
  [types.SAVE_SEEK_INDEX] (state, index) {
    state.seek.index = index;
    state.seek.indexGo = '';
  },
  [types.SAVE_QUERY_SESSION](state, req) {
    saveQuerySession(state, req);
  },
  [types.LOAD_OPTION_SOURCE] (state, option) {
    loadSource(state, option);
  },
  [types.LOAD_TRANSFORM] (state, req) {
    loadTransform(state, req);
  },
  [types.ADD_INLINE_ROW] (state) {
    var row = {}
    state.pageData.data.unshift(row);
    setTimeout(() => { state.inlineTableCom.setCurrentRow(row); }, 10);
  },
  [types.SET_INLINE_COM] (state, inlineTableCom) {
    state.inlineTableCom = inlineTableCom;
  },
  [types.DEL_INLINE_ROW] (state, scope) {
    var row = scope.row;
    var index = scope.$index;
    if (undefined === row.id) {
      state.pageData.data.splice(index, 1);
    }
  },
  [types.SAVE_INLINE_ROW](state, scope) {
    var row = scope.row;
    var index = scope.$index;
    var added = undefined === scope.row.id;
    var attrs = {
      type: 'main',
      uri: state.entry.uri,
    };
    delete row['__INLINE_MESSAGE__'];
    delete row['__INLINE_STATUS__'];
    delete row['__DRAFT_TIME__'];
    delete row['_id'];
    delete row['_class'];
    utils.ajax(state.entry.data.create.client.commit, row, attrs).then(res => {
      if (res.code == 200) {
        if (scope._self.currentRow == row) {
          scope._self.$refs.inlineTable.setCurrentRow(null);
        }
        Vue.delete(scope.row, '__INLINE_STATUS__');
        Vue.set(scope.row, '__INLINE_STATUS__', 'check-circle success');
        /* 注入ID, 以便后续操作 */
        if (added && res.data) {
          Vue.set(scope.row, 'id', res.data);
        }
      } else {
        scope.row['__INLINE_MESSAGE__'] = res.message;
        Vue.delete(scope.row, '__INLINE_STATUS__');
        Vue.set(scope.row, '__INLINE_STATUS__', 'times-circle danger');
      }
      notice(res);
    }, error => {
      Vue.delete(scope.row, '__INLINE_STATUS__');
      Vue.set(scope.row, '__INLINE_STATUS__', 'times-circle danger');
      notice({});
    });
    if ( ! scope.row['__INLINE_STATUS__']) {
      Vue.set(scope.row, '__INLINE_STATUS__', 'spinner fa-pulse');
    }
  },
  [types.AS_SEARCH_TEMPLATE](state, data) {
    if ( ! data.name) {
      notify({
        message: '请输入模板标题',
        type: 'error'
      });
      return;
    }
    var node = querySessionNode(state);
    if ( ! node.datas.length) {
      notify({
        showClose: true,
        message: '请设置搜索条件',
        type: 'error'
      });
      return;
    }

    data.uri = untransform(data.uri);
    data.node = node;
    axios.post(
      constant.API_SERVER + "/api/consume/asSearchTemplate?uri=" + data.uri,
      data,
    ).then(response => {
      if (200 == response.data.code) {
        notify({
          showClose: true,
          message: '操作成功',
          type: 'success'
        });
        loadSearchTemplate(state, data.uri);
      } else {
        notify({
          showClose: true,
          message: response.data.message ? '操作失败: ' + m(response.data.message) : '操作失败',
          type: 'error'
        });
      }
    }, response => {
        notify({
        showClose: true,
        message: '操作失败',
        type: 'error'
      });
    }
    );
  },
  [types.LOAD_SEARCH_TEMPLATE](state, uri) {
    loadSearchTemplate(state, uri);
  },
  [types.DEL_SEARCH_TEMPLATE](state, data) {
    data.uri = untransform(data.uri);
    axios.post(
      constant.API_SERVER + "/api/consume/delSearchTemplate?uri=" + data.uri + "&id=" + data.id,
    ).then(response => {
      if (200 == response.data.code) {
        notify({
          showClose: true,
          message: '操作成功',
          type: 'success'
        });
        loadSearchTemplate(state, data.uri);
      } else {
        notify({
          showClose: true,
          message: response.data.message ? '操作失败: ' + m(response.data.message) : '操作失败',
          type: 'error'
        });
      }
    }, response => {
        notify({
        showClose: true,
        message: '操作失败',
        type: 'error'
      });
    }
    );
  },
  [types.SWITCH_ACTIVE_NAME](state, req) {
    state.activeName = req.name;
  },
};
